<template>
  <div>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px" style="margin-top: 30px">
        <el-row>
          <el-col :span="10">
            <div class="user-info-head" @click="editCropper()">
              <div class="demo-image">
                  <span class="demonstration">添加商品图片</span>
                <br>
                  <el-image
                    style="width: 100px; height: 100px; object-fit: contain; border: 1px solid #eee;"
                    :src="options.img"
                    fit="fill">

                  </el-image>
              </div>
            </div>
            <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body @opened="modalOpened"  @close="closeDialog">
<!--              裁剪图片的区域-->
              <el-row>
                <el-col :xs="24" :md="12" :style="{height: '350px'}">
                  <!--            第三方插件 用于裁剪图片 -->
                  <vue-cropper
                    ref="cropper"
                    :img="options.img"
                    :info="true"
                    :autoCrop="options.autoCrop"
                    :autoCropWidth="options.autoCropWidth"
                    :autoCropHeight="options.autoCropHeight"
                    :fixedBox="options.fixedBox"
                    :outputType="options.outputType"
                    @realTime="realTime"
                    v-if="visible"
                  />

                </el-col>
<!--                旁边显示的裁剪后的图片-->
                <el-col :xs="24" :md="12" :style="{height: '350px'}">
                  <div class="Myavatar-upload-preview">
                    <img :src="previews.url" :style="previews.img" />
                  </div>
                </el-col>
              </el-row>
              <br />
              <el-row>
                <el-col :lg="2" :sm="3" :xs="3">
                  <!--          负责文件上传-->
                  <el-upload action="#"
                             :http-request="requestUpload"
                             :show-file-list="true"
                             :before-upload="beforeUpload"> <!--          上传前校验文件类型-->
                    <el-button size="small">
                      选择
                      <i class="el-icon-upload el-icon--right"></i>
                    </el-button>
                  </el-upload>

                </el-col>
<!--                缩放按钮-->
                <el-col :lg="{span: 1, offset: 2}" :sm="2" :xs="2">
                  <el-button icon="el-icon-plus" size="small" @click="changeScale(1)"></el-button>
                </el-col>
                <el-col :lg="{span: 1, offset: 1}" :sm="2" :xs="2">
                  <el-button icon="el-icon-minus" size="small" @click="changeScale(-1)"></el-button>
                </el-col>
                <el-col :lg="{span: 1, offset: 1}" :sm="2" :xs="2">
                  <el-button icon="el-icon-refresh-left" size="small" @click="rotateLeft()"></el-button>
                </el-col>
                <el-col :lg="{span: 1, offset: 1}" :sm="2" :xs="2">
                  <el-button icon="el-icon-refresh-right" size="small" @click="rotateRight()"></el-button>
                </el-col>



                <el-col :lg="{span: 2, offset: 6}" :sm="2" :xs="2">
                  <el-button type="primary" size="small" @click="conFirmImg()">确定</el-button>
                </el-col>

              </el-row>
            </el-dialog>



          </el-col>
        </el-row>

<!--        商品上传表单-->
        <el-row>
          <el-col :span="10">
            <el-form-item label="商品名称" prop="productName">
              <el-input v-model="form.productName" placeholder="请输入商品名称" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="10">
            <el-form-item label="商品SKU" prop="sku">
              <el-input v-model="form.sku" placeholder="请输入商品SKU" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="10">
            <el-form-item label="大分类" prop="categoryId1">
              <el-select v-model="form.categoryId1" placeholder="请选择分类" style="width: 100%">
                <el-option
                  v-for="item in categoryTree1"
                  :key="item.categoryId"
                  :label="item.categoryName"
                  :value="item.categoryId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="小分类" prop="categoryId2">
              <el-select v-model="form.categoryId2" placeholder="请选择分类" style="width: 100%">
                <el-option
                  v-for="item in categoryTree2"
                  :key="item.categoryId"
                  :label="item.categoryName"
                  :value="item.categoryId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-button type="primary" @click="addProductCategory1">添加大分类</el-button>
          <el-button type="primary" @click="addProductCategory2">添加小分类</el-button>
        </el-row>
        <el-row>
          <el-col :span="10">
            <el-form-item label="库存数量" prop="quantity">
              <el-input-number v-model="form.quantity" :min="0" placeholder="请输入库存数量" controls-position="right" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="商品成本价" prop="costPrice">
              <el-input-number v-model="form.costPrice" :min="0" placeholder="请输入商品成本价" controls-position="right" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="商品售价" prop="price">
              <el-input-number v-model="form.price" :min="0" placeholder="请输入商品售价" controls-position="right" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="10">
            <el-form-item label="商品描述" prop="description">
              <el-input
                v-model="form.description"
                placeholder="请输入商品描述"
                type="textarea"
                :rows="6"
                maxlength="500"
                show-word-limit
                class="description-textarea"
              />
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="是否上架" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio :label="1" class="radio-up">上架</el-radio>
                <el-radio :label="0" class="radio-down">下架</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormV2">确定添加</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    <el-dialog
      title="一级分类"
      :visible.sync="dialogVisible1"
      width="30%"
      :append-to-body="true">
      <el-form ref="categoryForm1" :model="categoryForm" :rules="categoryRules1">

        <el-form-item label="分类名称" prop="categoryName">
          <el-input v-model="categoryForm.categoryName" placeholder="请输入分类名称" />
        </el-form-item>

        <el-form-item label="分类描述" prop="description">
          <el-input v-model="categoryForm.description" placeholder="请输入分类描述" />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible1 = false">取消</el-button>
        <el-button type="primary" @click="submitCategory1">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="二级分类"
      :visible.sync="dialogVisible2"
      width="30%"
      :append-to-body="true">
      <el-form ref="categoryForm2" :model="categoryForm" :rules="categoryRules2">
        <el-form-item label="父分类" prop="parentId">
          <el-select v-model="categoryForm.parentId" placeholder="请选择父分类" style="width: 100%">
            <el-option
              v-for="item in categoryTree1"
              :key="item.categoryId"
              :label="item.categoryName"
              :value="item.categoryId">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="分类名称" prop="categoryName">
          <el-input v-model="categoryForm.categoryName" placeholder="请输入分类名称" />
        </el-form-item>

        <el-form-item label="分类描述" prop="description">
          <el-input v-model="categoryForm.description" placeholder="请输入分类描述" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible2 = false">取消</el-button>
        <el-button type="primary" @click="submitCategory2">确定</el-button>
      </div>

    </el-dialog>
  </div>
</template>

<script>
import { getCategoryName1,getCategoryName2,addProduct,addCategory1,addCategory2 ,addProductImg} from '@/api/inventory/add'
import store from "@/store"
import { VueCropper } from "vue-cropper"
import { uploadAvatar } from "@/api/system/user"
import { debounce } from '@/utils'
export default {
  name: "",
  components: { VueCropper },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 分类名称
      categoryTree1: [],//大分类
      categoryTree2: [],//小分类

      // 表单参数
      form: {
        productName: "", // 商品名称
        sku: "", // 商品SKU
        categoryId1: null, // 大分类 - 修改为null而非空字符串
        categoryId2: null, // 小分类 - 修改为null而非空字符串
        quantity: 0,   // 库存数量 - 修改为0而非空字符串
        costPrice: 0, // 成本价格 - 修改为0而非空字符串
        price: 0, // 售价 - 修改为0而非空字符串
        description: "", // 商品描述
        status: 1  // 是否上架 - 设置默认值为1(上架)
      },
      croppedImageBlob: null, // 存储裁剪后的图片blob数据
      // 表单校验
      rules: {
        productName: [ // 商品名称
          { required: true, message: "商品名称不能为空", trigger: "blur" }
        ],
        sku: [   // 商品SKU
          { required: true, message: "商品SKU不能为空", trigger: "blur" }
        ],
        categoryId1: [   // 分类
          { required: true, message: "大分类不能为空", trigger: "change" }
        ],
        categoryId2: [   // 小分类
          { required: true, message: "小分类不能为空", trigger: "change" }
        ],
        status: [   // 是否上架
          { required: true, message: "请选择上架状态", trigger: "change" }
        ]
      },

      dialogVisible1: false, // 分类弹窗显示状态
      dialogVisible2: false, // 分类弹窗显示状态

      categoryForm: { // 分类表单数据
        categoryName: '',
        parentId: null,
        description: ''
      },
      // 分类表单验证规则
      categoryRules1: {
        categoryName: [
          { required: true, message: "分类名称不能为空", trigger: "blur" },
          { min: 2, max: 20, message: "分类名称长度在 2 到 20 个字符", trigger: "blur" }
        ]
      },
      categoryRules2: {
        categoryName: [
          { required: true, message: "分类名称不能为空", trigger: "blur" },
          { min: 2, max: 20, message: "分类名称长度在 2 到 20 个字符", trigger: "blur" }
        ],
        parentId: [
          { required: true, message: "请选择父分类", trigger: "change" }
        ]
      },



      //图片上传

      // 是否显示弹出层
      open: false,
       //是否显示cropper
      visible: false,
      // 弹出层标题
      title: "上传商品图片",
      options: {
        img: 'https://example.com/default-product.png',  //裁剪图片的地址
        autoCrop: true,             // 是否默认生成截图框
        autoCropWidth: 300,         // 默认生成截图框宽度
        autoCropHeight: 300,        // 默认生成截图框高度
        fixedBox: true,             // 固定截图框大小 不允许改变
        outputType:"png",           // 默认生成截图为PNG格式
        filename: 'avatar'          // 文件名称
      },
      previews: {},
      resizeHandler: null
    }
  },
  methods: {
    // 获得分类名称 用于搜索
    getCategoryName() {
      getCategoryName1().then(Response => {
        console.log("获得后端返回的大分类名称",Response.data)
        this.categoryTree1 = Response.data
      }).catch(error => {
        console.error("获取大分类名称失败:", error);
      });
      getCategoryName2().then(Response => {
        console.log("获得后端返回的小分类名称",Response.data)
        this.categoryTree2 = Response.data
      }).catch(error => {
        console.error("获取小分类名称失败:", error);
      });

    },
    /** 确认提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          console.log("要提交的数据",this.form)
          addProduct(this.form).then(response => {
            this.$modal.msgSuccess("添加成功");
            this.$refs["form"].resetFields();

          }).catch(() => {
            this.$modal.msgError("添加失败");
          });

        }
      });
    },
    // 提交表单和上传图片
    submitFormV2() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 创建FormData对象
          let formData = new FormData();
          // 添加表单数据
          formData.append("productName", this.form.productName);
          formData.append("sku", this.form.sku);
          formData.append("categoryId1", this.form.categoryId1);
          formData.append("categoryId2", this.form.categoryId2);
          formData.append("quantity", this.form.quantity);
          formData.append("costPrice", this.form.costPrice);
          formData.append("price", this.form.price);
          formData.append("description", this.form.description);
          formData.append("status", this.form.status);

          // 添加图片文件（如果已选择）
          if (this.croppedImageBlob) {
            formData.append("productImage", this.croppedImageBlob, this.options.filename);
          }

          console.log("要提交的数据",this.form)
          // 提交表单和图片
          addProduct(formData).then(response => {
            this.$modal.msgSuccess("添加成功");
            this.$refs["form"].resetFields();
            // 上传成功后，清空 croppedImageBlob
            this.croppedImageBlob = null;
          }).catch(() => {
            this.$modal.msgError("添加失败");
          });

        }
      });
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.resetForm("form");
    },
    // 打开大分类弹窗
    addProductCategory1() {
      this.dialogVisible1 = true;
      this.$nextTick(() => {
        this.$refs.categoryForm1.resetFields();
      });
    },
    // 打开小分类弹窗
    addProductCategory2() {
      this.dialogVisible2 = true;
      this.$nextTick(() => {
        this.$refs.categoryForm2.resetFields();
      });
    },
    // 提交分类
    submitCategory1() {
      this.$refs.categoryForm1.validate(valid => {
        if (valid) {
          // console.log("添加大分类要提交的数据",this.categoryForm)
            addCategory1(this.categoryForm).then(response => {
              this.$modal.msgSuccess("大分类添加成功");
              this.dialogVisible1 = false;
              // 重新获取分类列表
              this.getCategoryName();
            }).catch(() => {
              this.$modal.msgError("大分类添加失败");
            });
        }
      });
      this.resetForm("categoryForm");
    },
    // 提交小分类
    submitCategory2() {
      this.$refs.categoryForm2.validate(valid => {
        if (valid) {
          // console.log("添加小分类要提交的数据",this.categoryForm)

            addCategory2(this.categoryForm).then(response => {
              this.$modal.msgSuccess("小分类添加成功");
              this.dialogVisible2 = false;
              // 重新获取分类列表
              this.getCategoryName();
            }).catch(() => {
              this.$modal.msgError("小分类添加失败");
            });

        }
      });
      this.resetForm("categoryForm");
    },

    //添加图片用
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },


    // 编辑商品图片
    editCropper() {
      this.open = true
    },
    // 打开弹出层结束时的回调
    modalOpened() {
      this.visible = true
      if (!this.resizeHandler) {
        this.resizeHandler = debounce(() => {
          this.refresh()
        }, 100)
      }
      window.addEventListener("resize", this.resizeHandler)
    },
    // 刷新组件
    refresh() {
      this.$refs.cropper.refresh()
    },
    // 覆盖默认的上传行为
    requestUpload() {
    },
    // 向左旋转
    rotateLeft() {
      this.$refs.cropper.rotateLeft()
    },
    // 向右旋转
    rotateRight() {
      this.$refs.cropper.rotateRight()
    },
    // 图片缩放
    changeScale(num) {
      num = num || 1
      this.$refs.cropper.changeScale(num)
    },
    // 上传预处理
    beforeUpload(file) {
      if (file.type.indexOf("image/") == -1) {
        this.$modal.msgError("文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件。")
      } else {
        const reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = () => {
          this.options.img = reader.result
          this.options.filename = file.name
        }
      }
    },
    // 上传图片
    uploadImg() {
      this.$refs.cropper.getCropBlob(data => {  // 获取裁剪后的图片 Blob 数据可直接用于文件上传
        let formData = new FormData()   // 创建 FormData 对象 用于存储上传的文件数据
        formData.append("Producefile", data, this.options.filename)
        //avatarfile：后端接口接收文件的参数名（需与后端约定一致）。
        //data：裁剪后的图片 Blob 数据（文件内容）。
        //this.options.filename：文件名（从用户选择的原始文件中获取，定义在 data 的 options 对象中）。
        addProductImg(formData).then(response => {
          this.open = false
          this.options.img =response.imgUrl
          store.commit('SET_AVATAR', this.options.img)
          this.$modal.msgSuccess("修改成功")
          this.visible = false
        })
      })
    },
    // 实时预览
    realTime(data) {
      this.previews = data
    },
    // 关闭窗口
    closeDialog() {
      this.options.img =this.previews.url
      this.visible = false
      window.removeEventListener("resize", this.resizeHandler)
    },
    // 确认图片
    conFirmImg() {
      this.$refs.cropper.getCropBlob(data => {
        this.croppedImageBlob = data; // 保存裁剪后的图片blob数据
        this.options.img = URL.createObjectURL(data); // 预览图片
        this.$modal.msgSuccess("图片已准备好，提交表单时将一并上传");
        this.visible = false;
      });

      //this.options.img = this.previews.url
      this.open = false
      //this.visible = false
      window.removeEventListener("resize", this.resizeHandler)
    }




  },
  created() {
    this.getCategoryName()
  }
}
</script>

<style scoped lang="scss">
/* 上架状态-绿色 */
::v-deep .radio-up .el-radio__label {
  color: #4CAF50;
}
::v-deep .radio-up .el-radio__input.is-checked .el-radio__inner {
  border-color: #4CAF50;
  background: #4CAF50;
}

/* 下架状态-红色 */
::v-deep .radio-down .el-radio__label {
  color: #F44336;
}
::v-deep .radio-down .el-radio__input.is-checked .el-radio__inner {
  border-color: #F44336;
  background: #F44336;
}
/* 商品描述文本框样式优化 */
::v-deep .description-textarea .el-textarea__inner {
  padding: 10px 12px;  /* 优化内边距 */
  border-radius: 4px;  /* 轻微圆角 */
  resize: vertical;    /* 允许垂直调整大小 */
  min-height: 120px;   /* 设置最小高度 */
}

.user-info-head {
  position: relative;
  display: inline-block;
  height: 120px;
}

.user-info-head:hover:after {
  content: '+';
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  color: #eee;
  background: rgba(0, 0, 0, 0.5);
  font-size: 24px;
  font-style: normal;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  cursor: pointer;
  line-height: 110px;
  border-radius: 50%;
}

.Myavatar-upload-preview {
  position: relative;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 300px;
  height: 300px;
  //border-radius: 50%;
  box-shadow: 0 0 4px #ccc;
  overflow: hidden;
}
</style>
